import bean.Developer;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author: zhangxupeng
 * @date:2019/5/10
 * @Email: zhangxupeng@bilibili.com
 **/
public class TestStreamCollectorsGroupingBy {
    public static void main(String[] args) {
//        groupBy();


        groupByField();
    }

    private static void groupByField() {
        List<Developer> items = Arrays.asList(
                new Developer("apple", new BigDecimal("9.99"), 10),
                new Developer("banana", new BigDecimal("19.99"), 20),
                new Developer("orang", new BigDecimal("29.99"), 10),
                new Developer("watermelon", new BigDecimal("29.99"), 10),
                new Developer("papaya", new BigDecimal("9.99"), 20),
                new Developer("apple", new BigDecimal("9.99"), 10),
                new Developer("banana", new BigDecimal("19.99"), 10),
                new Developer("apple", new BigDecimal("9.99"), 20)
        );

        Map<String, Long> counting = items.stream().collect(
                Collectors.groupingBy(Developer::getName, Collectors.counting()));

        System.out.println(counting);

        Map<String, Integer> sum = items.stream().collect(
                Collectors.groupingBy(Developer::getName, Collectors.summingInt(Developer::getAge)));

        System.out.println(sum);

        //group by salary
        Map<BigDecimal, List<Developer>> groupByPriceMap =
                items.stream().collect(Collectors.groupingBy(Developer::getSalary));

        System.out.println(groupByPriceMap);

        // group by price, uses 'mapping' to convert List<Developer> to Set<String>
        Map<BigDecimal, Set<String>> result =
                items.stream().collect(
                        Collectors.groupingBy(Developer::getSalary,
                                Collectors.mapping(Developer::getName, Collectors.toSet())
                        )
                );

        System.out.println(result);


    }

    private static void groupBy() {
        //3 apple, 2 banana, others 1
        List<String> items =
                Arrays.asList("apple", "apple", "banana",
                        "apple", "orange", "banana", "papaya");

        Map<String, Long> result =
                items.stream().collect(
                        Collectors.groupingBy(
                                Function.identity(), Collectors.counting()
                        )
                );

        System.out.println(result);

        //加入排序
        Map<String, Long> finalMap = new LinkedHashMap<>();

        //Sort a map and add to finalMap
        result.entrySet().stream()
                .sorted(Map.Entry.<String, Long>comparingByValue()
                        .reversed()).forEachOrdered(e -> finalMap.put(e.getKey(), e.getValue()));

        System.out.println(finalMap);
    }
}
